package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/7/10 15:36
 * @description：https://leetcode-cn.com/problems/sort-characters-by-frequency/
 */
public class 根据字符出现频率排序 {
    @Test
    public void test() {
        Solution solution = new Solution();
    }

    class Solution {
        public String frequencySort(String s) {
            HashMap<Character, Integer> map = new HashMap<>();
            for (char c : s.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            ArrayList<Letter> letters = new ArrayList<>();
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                letters.add(new Letter(entry.getKey(), entry.getValue()));
            }
            letters.sort((o1, o2) -> o1.count - o2.count);
            StringBuilder builder = new StringBuilder();
            for (Letter letter : letters) {
                for (int i = 0; i < letter.count; i++) {
                    builder.append(letter.val);
                }
            }
            return builder.toString();
        }
    }

    class Letter {
        char val;
        int count;

        public Letter(char val, int count) {
            this.val = val;
            this.count = count;
        }
    }
}
